#!/usr/bin/python3
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# ******************************************************************************/


class Api:
    """
    bugzilla api
    """

    def __init__(self, base_url):
        self.host = base_url

    def _parse_query_param(self, params):
        """
        Parse the request parameters of the query
        """
        try:
            query_str = []
            for key, value in params.items():
                query_str.append("{key}={value}".format(key=key, value=value))
            return "&".join(query_str)
        except AttributeError:
            return query_str

    def get_bug(self, fields, **kwargs):
        """
        To get information about a particular bug using its ID or alias

        You can also use Search Bugs to return more than one bug at a time
        by specifying bug IDs as the search terms

        """

        if isinstance(fields, (str, int)):
            rest_api = '/rest/bug/{}'.format(fields)
        if isinstance(fields, dict):
            rest_api = "/rest/bug?{query_param}".format(
                query_param=self._parse_query_param(params=fields))

        return self.host + rest_api

    def get_comments(self, fields, is_comment_id=False, **kwargs):
        """
        To get all comments for a particular bug using the bug ID or alias

        To get a specific comment based on the comment ID

        """
        if is_comment_id:
            rest_api = '/rest/bug/comment/{comment_id}'.format(
                comment_id=fields)
        else:
            rest_api = '/rest/bug/{id_or_alias}/comment'.format(
                id_or_alias=fields)

        return self.host + rest_api
